package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.ContactUser;
import util.DBHelp;
import util.RowMapper;

public class ContactUserDao {

    DBHelp<ContactUser> db = new DBHelp<ContactUser>();

    public List<ContactUser> findByContactId(int contactId) {
        String sql = "SELECT bmw_contact_has_bmw_user.id, bmw_contact_id, bmw_user_id, message, TIME , NAME AS bmw_user_name FROM bmw_contact_has_bmw_user, bmw_user WHERE bmw_contact_id = ? AND bmw_contact_has_bmw_user.bmw_user_id = bmw_user.id order by time desc";
        return db.excuteForList(sql, new ContactUserRowMapper(), contactId);
    }

    public int addContactUser(ContactUser contactUser) {

        String sql = "insert into bmw_contact_has_bmw_user (message, time, bmw_user_id, bmw_contact_id) value(?,?,?,?) ";
        return db.excuteSQL(sql, contactUser.getMessage(),
                System.currentTimeMillis(), contactUser.getUserId(),
                contactUser.getContactId());
    }

    public int delContactUser(int id) {
        String sql = "delete from bmw_contact_has_bmw_user where id = ?";
        return db.excuteSQL(sql, id);
    }

    public int delBycontactId(int contactId) {
        String sql = "delete from bmw_contact_has_bmw_user where bmw_contact_id = ?";
        return db.excuteSQL(sql, contactId);
    }

    private class ContactUserRowMapper implements RowMapper<ContactUser> {

        @Override
        public ContactUser mapperRow(ResultSet rs) throws SQLException {
            ContactUser contactUser = new ContactUser();
            contactUser.setId(rs.getInt("id"));
            contactUser.setContactId(rs.getInt("bmw_contact_id"));
            contactUser.setMessage(rs.getString("message"));
            contactUser.setTime(rs.getLong("time"));
            contactUser.setUserId(rs.getInt("bmw_user_id"));
            contactUser.setUserName(rs.getString("bmw_user_name"));
            return contactUser;
        }

    }

}
